package com.oraro.paygatewaybiz.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: jianghuiyong
 * @Date: 2018/12/3 17:52
 * @Version 1.0
 */
@Configuration
@EnableAsync
public class ExecutorPoolConfig implements AsyncConfigurer {


    @Value("${executor.corePoolSize: 10}")
    private int corePoolSize;
    @Value("${executor.maxPoolSize: 50}")
    private int maxPoolSize;
    @Value("${executor.queueSize: 250}")
    private int queueSize;
    @Value("${executor.keepAlive: 60}")
    private int keepAlive;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程，都会给新的任务产生新的线程
        int cores = Runtime.getRuntime().availableProcessors();
        taskExecutor.setCorePoolSize(corePoolSize);
        //连接池中保留的最大连接数。Default: 15 maxPoolSize
        taskExecutor.setMaxPoolSize(maxPoolSize);
        //queueCapacity 线程池所使用的缓冲队列
        taskExecutor.setQueueCapacity(queueSize);
        //如果线程数多于corePoolSize,则这些多余的线程的空闲时间超过keepAliveTime时将被终止
        taskExecutor.setKeepAliveSeconds(keepAlive);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        taskExecutor.setThreadNamePrefix("ExecutorPool-");
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        // TODO Auto-generated method stub
        return null;
    }

}
